package com.hdl.api;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

/**
 * 类名 CreateSession
 * 描述 删除节点
 *
 * @author hedonglin
 * @version 1.0
 * @date 2020/6/14 12:27
 */
public class DeleteNode implements Watcher {

    private static ZooKeeper zooKeeper;

    /**
     * 建立会话并删除节点
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        /**
         * 客户端可以通过创建一个zk实例来连接zk服务器
         * new Zookeeper(connectString, sessionTimeOut, Watcher)
         * connectString连接地址， IP：端口
         * sessionTimeOut： 会话超时时间，单位毫秒
         * Watcher：监听器（当特定事件触发监听时，zk会通过watcher通知客户端）
         */
        zooKeeper = new ZooKeeper("192.168.227.131:2181", 3000, new DeleteNode());
        Thread.sleep(Integer.MAX_VALUE);
    }

    /**
     * 回调方法，处理来自服务器端的Watcher通知
     *
     * @param event
     */
    public void process(WatchedEvent event) {
        // SyncConnected
        if (event.getState() == Event.KeeperState.SyncConnected) {
            System.out.println("process方法被执行了....");
            try {
                deleteNodeSync();
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 删除数据节点
     * zooKeeper.exists(path,watch) :判断节点是否存在
     * zookeeper.delete(path,version) : 删除节点
     */
    private void deleteNodeSync() throws KeeperException, InterruptedException {
        System.out.println("================删除前=================");
        Stat stat = zooKeeper.exists("/hdl-persistent/c1", false);
        System.out.println(stat == null ? "该节点不存在" : "该节点存在");
        if (stat != null){
            zooKeeper.delete("/hdl-persistent/c1", -1);
        }
        System.out.println("================删除后=================");
        Stat stat2 = zooKeeper.exists("/hdl-persistent/c1", false);
        System.out.println(stat2 == null ? "该节点不存在" : "该节点存在");
    }
}
